package com.shanyin.framework.member.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shanyin.framework.common.base.BaseServiceImpl;
import com.shanyin.framework.common.base.ResponseData;
import com.shanyin.framework.common.base.ResponseStatus;
import com.shanyin.framework.common.util.InviteCodeUtil;
import com.shanyin.framework.common.util.MD5Util;
import com.shanyin.framework.common.util.StringUtil;
import com.shanyin.framework.common.util.ValidateUtil;
import com.shanyin.framework.member.dao.SysUserDao;
import com.shanyin.framework.member.dao.SysUserInfoDao;
import com.shanyin.framework.member.dao.SysUserInviteDao;
import com.shanyin.framework.member.entity.SysUser;
import com.shanyin.framework.member.entity.SysUserInfo;
import com.shanyin.framework.member.entity.SysUserInvite;
import com.shanyin.framework.member.enums.SysUserEnum;
import com.shanyin.framework.member.service.SysUserService;

/**
 * @author qing.yunhui 
 * @Since 2011-2018
 * @create 2018-05-23 14:35:32
 * @history
 */
@Service("sysUserService")
public class SysUserServiceImpl extends BaseServiceImpl<SysUser,Long> implements SysUserService{

	Logger logger=LoggerFactory.getLogger(getClass());
	
	@Autowired
	SysUserDao sysUserDao;
	
	@Autowired
	SysUserInviteDao sysUserInviteDao;
	
	@Autowired
	SysUserInfoDao sysUserInfoDao;
	
	@Override
	public ResponseData registered(String phone, String password, String registerChannel, String invitationCode) {
		ResponseData responseData=new ResponseData();
		if(StringUtil.isEmptys(phone,password)) {
			logger.error("==============>注册需要的phone={},password={}.为NULL.注册失败!",new Object[] {phone,password});
			return new ResponseData(ResponseStatus.FAILED, "Parameter is null.");
		}
		//@1.校验注册的手机号格式是否正确
		if(!ValidateUtil.isMobile(phone)) {
			logger.error("==============>phone={}的手机号格式不正确!",new Object[] {phone});
			return new ResponseData(ResponseStatus.FAILED, "Not a correct phone number.");
		}
		//@2.查询该phone是否已注册. 
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("phone", phone);
		int count=sysUserDao.queryCount(map);
		if(count>0) {
			logger.error("==============>phone={}的手机号已被注册.",new Object[] {phone});
			return new ResponseData(ResponseStatus.FAILED, "Phone number has been registered.");
		}
		//@3.如果邀请码不为null、则需要查询对应的邀请码对应的用户是否存在.
		SysUserInvite userInvite=null;
		if(StringUtil.isNotEmptys(invitationCode)) {
			SysUser inviteUser=sysUserDao.getSysUserByInvitationCode(invitationCode);
			if(null==inviteUser){
				logger.error("==============>invitationCode={}邀请码不存在.",new Object[] {invitationCode});
				return new ResponseData(ResponseStatus.FAILED, "The invitation code does not exist.");
			}
			userInvite=new SysUserInvite(inviteUser.getId(), null);
		}
		String genInviteCode=genInviteCode();
		SysUser sysUser=new SysUser(phone, MD5Util.getMD5DoubleEncryption(password, genInviteCode), genInviteCode, registerChannel,SysUserEnum.STATUS.VALID.getKey());
		//@4.用户入库后、需要同时往邀请表插入一条记录、
		int rows=sysUserDao.insert(sysUser);
		sysUserInfoDao.insert(new SysUserInfo(sysUser.getId()));
		if(rows>0 && null!=userInvite) {
			userInvite.setInviteeUserId(sysUser.getId());
			sysUserInviteDao.insert(userInvite);
		}
		return responseData;
	}
	
	@Override
	public ResponseData login(String account,String password,boolean isPhone) {
		if(StringUtil.isEmptys(account,password)) {
			logger.error("==============>登陆需要的账号={},password={}.为NULL.登陆失败!",new Object[] {account,password});
			return new ResponseData(ResponseStatus.FAILED, "Parameter is null.");
		}
		//@1.校验注册的手机号格式是否正确
		if(isPhone && !ValidateUtil.isMobile(account)) {
			logger.error("==============>phone={}的手机号格式不正确!",new Object[] {account});
			return new ResponseData(ResponseStatus.FAILED, "Not a correct phone number.");
		}
		//@2.查询账号在user表是否存在
		SysUser user=isPhone?sysUserDao.getSysUserByPhone(account):sysUserDao.getSysUserByEmail(account);
		if(null==user) {
			logger.error("==============>账号={}的用户不存在，登陆失败!",new Object[] {account});
			return new ResponseData(ResponseStatus.FAILED, "User does not exist.");
		}
		//@3.查询账号在userInfo表中是否存在
		SysUserInfo userInfo=sysUserInfoDao.getSysUserInfoByUserId(user.getId());
		if(null==userInfo) {
			logger.error("==============>账号={}的userId={}的用户在SysUserInfo中不存在，登陆失败!",new Object[] {account,user.getId()});
			return new ResponseData(ResponseStatus.FAILED, "Account exception.");
		}
		//@4.密码输入是否正确
		String inputPassword=MD5Util.getMD5DoubleEncryption(password, user.getInvitationCode());
		if(!inputPassword.equals(user.getPassword())) {
			logger.error("==============>账号={}的用户密码输入有误，登陆失败!",new Object[] {account});
			return new ResponseData(ResponseStatus.FAILED, "Incorrect password.");
		}
		//@5.用户状态是否异常
		if(!user.getStatus().equals(SysUserEnum.STATUS.VALID.getKey())) {
			logger.error("==============>账号={}的用户状态异常，登陆失败!",new Object[] {account});
			return new ResponseData(ResponseStatus.FAILED, "Account exception.");
		}
		return new ResponseData();
	}
	
	@Override
	public SysUser getSysUserByPhone(String phone) {
		if(StringUtil.isEmptys(phone)) {
			logger.error("==============>Parameter cannot be null.");
			throw new NullPointerException();
		}
		return sysUserDao.getSysUserByPhone(phone);
	}

	@Override
	public SysUser getSysUserByInvitationCode(String invitationCode) {
		if(StringUtil.isEmptys(invitationCode)) {
			logger.error("==============>Parameter cannot be null.");
			throw new NullPointerException();
		}
		return sysUserDao.getSysUserByInvitationCode(invitationCode);
	}
	
	/**
	 * <p>生成6位数的邀请码</p>
	 * @return 
	 * */
	private String genInviteCode() {	
		while(true) {
			String invitationCode=InviteCodeUtil.genInviteCode(6);
			if(sysUserDao.queryCountByInvitationCode(invitationCode)==0) {
				return invitationCode;
			}
		}
	}

}